package pers.xuehongyan.useat.server.service;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import pers.xuehongyan.useat.server.enity.User;
import pers.xuehongyan.useat.server.exception.ServiceException;
import pers.xuehongyan.useat.server.exception.user.UserAuthenticationFailException;
import pers.xuehongyan.useat.server.exception.user.UserNotFoundException;
import pers.xuehongyan.useat.server.manager.UserManager;

import javax.annotation.Resource;

/**
 * @author xuehongyan
 */
@Service
public class UserService {

    @Resource
    UserManager userManager;

    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    public void register(String username, String passwordRaw) {
        String passwordSecret = bCryptPasswordEncoder.encode(passwordRaw);
        User user = new User(username, passwordSecret);
        userManager.create(user);
    }

    public String login(String username, String passwordRaw) throws ServiceException {
        String passwordSecret = bCryptPasswordEncoder.encode(passwordRaw);
        User user = userManager.getUserByName(username);
        if(user.getPassword().equals(passwordSecret)) {
            throw new UserAuthenticationFailException();
        }
        return userManager.getTokenByUser(user);
    }

    public User getUserByToken(String token) throws UserNotFoundException {
        return userManager.getUserByToken(token);
    }
}
